package com.yorkfeng.blemulti.Adapter;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.yorkfeng.blemulti.R;
import com.yorkfeng.blemulti.Utils.Constants;

import java.util.ArrayList;

/**
 * Created by yorkfeng on 16/11/14.
 */
public final class BAdapter extends BaseAdapter {
    ArrayList<BluetoothDevice> arraySource;
    private LayoutInflater factory;
    private Context context;

    public BAdapter(Context context, ArrayList<BluetoothDevice> arraySource) {
        this.context = context;
        this.arraySource = arraySource;
        factory = LayoutInflater.from(this.context);
    }

    @Override
    public int getCount() {
        return arraySource.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        DeviceItem item = null;
        if (convertView == null) {
            convertView = factory.inflate(R.layout.listitem_device, null);
            item = new DeviceItem();
            item.deviceName = (TextView) convertView.findViewById(R.id.device_name);
            item.deviceAddress = (TextView) convertView.findViewById(R.id.device_address);
            convertView.setTag(item);
        }
        else {
            item = (DeviceItem) convertView.getTag();
        }

        BluetoothDevice device = arraySource.get(position);
        String name = device.getName();

        // 从文件中读取文件名
        SharedPreferences pres = context.getSharedPreferences(Constants.CONFIG_FILE_NAME, Context.MODE_PRIVATE);
        String deviceName = pres.getString(device.getAddress(), "");
        // 文件中已存在该设备名，采用该设备名
        if ((deviceName.length() != 0) && !name.equals(deviceName)) {
            name = deviceName;
        }

        if (name != null && !name.equals(""))
            item.deviceName.setText(name);
        else
            item.deviceName.setText("NO data");
        item.deviceAddress.setText(device.getAddress());

        return convertView;
    }

    private class DeviceItem {
        TextView deviceName;
        TextView deviceAddress;
    }
}

